<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";


class LeftMenu extends IPlugin
{
        function LeftMenu($parent = null)
        {
                IPlugin::IPlugin($parent);
                $this->tplfolder = dirname(__FILE__)."/tpl";
        }

        function getPluginTag() { return "leftmenu"; }
        function getPluginName() { return "Left Menu Plugin"; }
        function getPluginVersion() { return "1.0.0"; }

        function getProperty($p = null)
        {
                if(null == $p)
                {
                        return array("MenuBlockTitle", "MenuTitle");
                }
                $result = "";
                switch ($p)
                {
                        case "MenuBlockTitle": { return "Left Menu"; } break;
                        case "MenuTitle" : { return "Left Menu"; } break;
                };
                return $result;
        }

        // ----------------------------------------------------------------------------------
        // --- [ Handling all actions ] -----------------------------------------------------
        // ----------------------------------------------------------------------------------

        function doAction($params)
        {
                if(null != ($result = IPlugin::doAction($params)))
                {
                        return $result;
                }
                elseif ("doAddMenuItem" == $_POST['action'])
                {
                        $z = $_POST;
                        $uid = $z["id"];
                        $menuid = $z['menuid'];
                        
                        $z['parent_id'] = $_GET['menuid'];
                        $timestamp = getdate();
                        $copy_to = "left_menu/".$z['parent_id']."_".$timestamp[0];
                        @uploadFile('img_on',"/inventory/".$copy_to."_on.jpg");
                        if(isne($_FILES['img_on']['tmp_name']))
                                $z['img_on'] = $copy_to."_on.jpg";
                        @uploadFile('img_off',"/inventory/".$copy_to."_off.jpg");       
                        if(isne($_FILES['img_off']['tmp_name']))
                                $z['img_off'] = $copy_to."_off.jpg";
                                
                        unset($z["action"], $z["id"],$z['menuid']);
                        if( !in_array('is_active',array_keys($z)))
                        {
                                $z["is_active"] = 'N';
                        }
                        else 
                        {
                                if('on' == $z['is_active'])
                                {
                                        $z["is_active"] = 'Y';
                                }
                                
                        }
                        // url
                        if(isne($z['url'][1]))
                        {
                                $z['url'] = $z['url'][1];
                        }elseif(-1 != $z['url'][0])
                        {
                                $z['url'] = $z['url'][0];
                        }
                        else 
                        {
                                $z['url'] = "/";
                        }
                        //  eof url
                        $keys = "";
                        $vars = "";
                        foreach ($z as $k => $v)
                        {
                                $keys .=($keys=="" ? "" : ", ")."{$k}";
                                $vars .=($vars=="" ? "" : ", ")."'".str2db($v)."'";
                        }

                        $sql="insert into left_menu ({$keys}) values({$vars}) ";
                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        $db->Exec($sql);
                        
                }elseif ("doEditMenuItem" == $_POST['action'])
                {
                        $z = $_POST;
                        $uid = $z["id"];
                        $menuid = $z['menuid'];
                        
                        $z['parent_id'] = $_GET['menuid'];
                        $timestamp = getdate();
                        $copy_to = "left_menu/".$z['parent_id']."_".$timestamp[0];
                        @uploadFile('img_on',"/inventory/".$copy_to."_on.jpg");
                        if(isne($_FILES['img_on']['tmp_name']))
                                $z['img_on'] = $copy_to."_on.jpg";
                        @uploadFile('img_off',"/inventory/".$copy_to."_off.jpg");       
                        if(isne($_FILES['img_off']['tmp_name']))
                                $z['img_off'] = $copy_to."_off.jpg";
                                
                        unset($z["action"], $z["id"],$z['menuid']);
                        if( !in_array('is_active',array_keys($z)))
                        {
                                $z["is_active"] = 'N';
                        }
                        else 
                        {
                                if('on' == $z['is_active'])
                                {
                                        $z["is_active"] = 'Y';
                                }
                                
                        }
                        // url
                        if(isne($z['url'][1]))
                        {
                                $z['url'] = $z['url'][1];
                        }elseif(-1 != $z['url'][0] && $z['url'][0] != '')
                        {
                                $z['url'] = $z['url'][0];
                        }
                        else 
                        {
                                $z['url'] = "./";
                        }
                        //EOf url
                        
                        $set = "";
                        foreach ($z as $k => $v)
                        {
                                $set .= ($set=="" ? "" : ", ")."{$k} = '".str2db($v)."'";                               
                        }

                        $sql="update left_menu set {$set} where menuid='{$menuid}'";
                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
//                      debug($sql);
                        $db->Exec($sql);
                        
                }elseif("swap" == $_POST['action'])
                {
                        $chbx = $_POST['chbx'];
                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        
                        $q=" select menuid,sibling from left_menu where menuid in ({$chbx[0]},{$chbx[1]})";
                        $res = $db->getAll($q);
                        $arg = array(
                                array($res[1][sibling], $res[0][menuid]),
                                array($res[0][sibling], $res[1][menuid]),
                        );
                        
                        $db->Exec("update left_menu set sibling=? where menuid=?",0, $arg);
                        
                }elseif("insert_after" == $_POST['action'])
                {
                        $chbx = $_POST['chbx'];
                        $sibling_count = $_POST['sibling_count'];
                        
                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        $not_in =="";
                        for($i = 0; $i<sizeof($chbx); $i++){
                                $not_in .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
                        }
                        $q=" select menuid,sibling from left_menu where sibling> '{$sibling_count}' and menuid not in ({$not_in})";
                        $res = $db->getAll($q);
                        
                        $arg = array();
                        for($i = 0 ; $i <sizeof($chbx);$i++){
                                $arg[$i] = array(++$sibling_count,$chbx[$i]);
                        }
                        for($i = 0 ; $i <sizeof($res);$i++){
                                $arg[] = array(++$sibling_count,$res[$i]['menuid']);
                        }
                        $db->Exec("update left_menu set sibling=? where menuid=?",0, $arg);
                        
                        
                }elseif("insert_before" == $_POST['action'])
                {
                        $chbx = $_POST['chbx'];
                        $sibling_count = $_POST['sibling_count'];
                        
                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        $not_in =="";
                        for($i = 0; $i<sizeof($chbx); $i++){
                                $not_in .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
                        }
                        $q=" select menuid,sibling from left_menu where sibling >= '{$sibling_count}' and menuid not in ({$not_in}) order by sibling";
                        $res = $db->getAll($q);
                        
                        $arg = array();
                        for($i = 0 ; $i <sizeof($chbx);$i++){
                                $arg[$i] = array($sibling_count++,$chbx[$i]);
                        }
                        for($i = 0 ; $i <sizeof($res);$i++){
                                $arg[] = array($sibling_count++,$res[$i]['menuid']);
                        }
                        $db->Exec("update left_menu set sibling=? where menuid=?",0, $arg);
                        
                }elseif("sibling_delete" == $_POST['action'])
                {
                        $chbx = $_POST['chbx'];
                        $sibling_count = $_POST['sibling_count'];
                        
                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        $not_in =="";
                        for($i = 0; $i<sizeof($chbx); $i++){
                                $not_in .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
                        }
                        $q="delete from left_menu where menuid in ({$not_in})";
                        $db->Exec($q);
                }

                if("doDeleteMenuItem" == $_GET['action'])
                {
                        $uid = $_GET['id'];
                        if(empty($uid) || $uid<0 || !is_numeric($uid) )
                        {
                                header("location: ./index.php?".$this->getURL());
                                exit();
                        }
                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        
                        $sql = "delete from left_menu where menuid=".str2db($uid)."";
                        $item = $db->getRow("select img_on,img_off from left_menu where menuid=".str2db($uid)."");
                        @unlink($core->config["file_root"] . "/inventory/".$item['img_on']);
                        @unlink($core->config["file_root"] . "/inventory/".$item['img_off']);
                        $db->Exec($sql);

                        header("location: ./index.php?".$this->getURL());
                        exit();
                        
                }
                
                return true;
        }

        // ----------------------------------------------------------------------------------
        // --- [ Render pages ] -------------------------------------------------------------
        // ----------------------------------------------------------------------------------

        function Render($params)
        {
                global $_G;
                if(null != ($result = IPlugin::Render($params)))
                {
                        return $result;
                }

                $core = &getCoreInstance();
                $db = $core->getProperty("db");
                $framework = $core->getProperty("framework");
                $render = $framework->smarty;

                $page = "";

                switch ($_G["page"]) {
                        case "add":
                                $page = $this->renderLeftMenuAdd($core, $render, $db);
                                break;
                        case "edit":
                                $page = $this->renderLeftMenuEdit($core, $render, $db);
                                break;
                        default:
                                $page = $this->renderLeftMenu($core, $render, $db);
                                break;
                }

                return $render->fetch("file:".$this->tplfolder."/".$page);
        }


        // ----------------------------------------------------------------------------------
        // --- [ Generate Customers List ] --------------------------------------------------
        // ----------------------------------------------------------------------------------
        function cb_renderLeftMenu($data)
        {
                $img_on         = $data["img_on"];
                $img_off        = $data["img_off"];
                $img_html = "";
                if( isne($img_on) or isne($img_off))
                {
                        $img_html = "<a href='?".$this->getURL()."&page=edit&menuid=".$data["menuid"]."' >";
                        if(isne($img_on))
                                $img_html .="<img src='/inventory/{$img_on}' border=2 \"/>";
                        if(isne($img_off))
                                $img_html .="<img src='/inventory/{$img_off}' border=2 \"/>";
                                
                        $img_html .="</a>";
                }
                else
                {
                        $img_html = "No Image";
                }
                $dt = array(
                array("<input type='checkbox' name='chbx[]' value='{$data["menuid"]}' />", "align='center' "),
                array($data["menuid"] , "align=\"center\""),
                array($data["sibling"] , "align=\"center\""),
                array($img_html , ""),
                array( "<a href='?".$this->getURL()."&page=edit&menuid=".$data["menuid"]."' >".$data["title"]."</a>", ""),
                array('Y'==$data["is_active"]?"Yes":"No" , "align='center'"),
                array("<a href=\"?".$this->getURL()."&page=edit&menuid={$data[menuid]}&id={$data[menuid]}\">edit</a>&nbsp;<a href=\"?".$this->getURL()."&action=doDeleteMenuItem&id={$data[menuid]}\">delete</a>" , "align=\"center\"")
                );
                return $dt;
        }

        function renderLeftMenuEdit(&$core ,&$render , &$db)
        {
                $menuid = $_GET['menuid'];
                if(isne($_GET['menuid']))
                {
                        if($menuid<0 || !is_numeric($menuid)){
                                header("location: ./index.php?".$this->getURL());
                                exit();
                        }
                }
                else 
                {
                        $menuid = 0;
                }
                if(0!=$menuid)
                {
                        $res_db = $db->getAll("select * from left_menu where menuid='{$menuid}'");
                        $render->assign('item',$res_db[0]);
                        $render->assign('id',$menuid);
                }
                
                $render->assign("url", "?".$this->getURL()."&menuid=".$menuid);
                $render->assign("cancel_url", "?".$this->getURL());
                $render->assign("action", 'doEditMenuItem');
                $render->assign("title", 'Add Left Menu Item');
                
#               $res_action = "";
#               getAllHistory(0,"",$res_action);
                $res_action = $db->getAll("select catalog_id, title  from catalog where parent_id = 0 and is_category = 'Y' and display_in_menu = 'Y' order by sibling asc");
                $render->assign('res_action',$res_action);
                #$render->assign('res_action',$res_action);
                
                return "leftmenuedit.tpl.php";
        }
        
        function renderLeftMenuAdd(&$core ,&$render , &$db)
        {
                $menuid = $_GET['menuid'];
                if(isne($_GET['menuid']))
                {
                        if($menuid<0 || !is_numeric($menuid)){
                                header("location: ./index.php?".$this->getURL());
                                exit();
                        }
                }
                else 
                {
                        $menuid = 0;
                }
                $render->assign("url", "?".$this->getURL()."&menuid=".$menuid);
                $render->assign("cancel_url", "?".$this->getURL());
                $render->assign("action", 'doAddMenuItem');
                $render->assign("title", 'Add Left Menu Item');
                
#               $res_action = "";
                $res_action = $db->getAll("select catalog_id, title  from catalog where parent_id = 0 and is_category = 'Y' and display_in_menu = 'Y' order by sibling asc");
                $render->assign('res_action',$res_action);

                #getAllHistory(0,"",$res_action);
                #$render->assign('res_action',$res_action);
                
                return "leftmenuedit.tpl.php";
        }
        
        function renderLeftMenu(&$core, &$render, &$db)
        {
                $ctglist = array();
                //              getAllHistory(0, "", $ctglist);
                //              $render->assign("categorieslist", $ctglist);
                //              $render->assign("categoryid", $_GET["id"]);
                //              list
                $sb = &$core->getSnippet("sibling");
                $sibling_params = array(
                "action"                =>"removeWrongSibling",
                "table"                 =>"left_menu",
                "sField"                =>"sibling", // ordering field
                "sId"                   =>"menuid",
                "sParentId"             =>"parent_id",
                "sWhere"                =>"is_active = 'Y'",
                );
                $sb -> doAction($sibling_params);// remove sibling = -1

                // ===== end of  sibling = -1*/

                $db_res = $db->getAll("select * from left_menu order by sibling");
                //              debug($db_res[0]);
                for($i = 0 ;$i<sizeof($db_res) ;$i++)
                {
                        $db_res[$i] = $this->cb_renderLeftMenu($db_res[$i]);
                }
                $render->assign("title", "Left Menu Items List");
                $render->assign("items", $db_res);
                $render->assign("empty_message", "Empty Menu Items List");

                $res_folder_str = "";
                for($i= 0 ; $i < sizeof($res) ; $i++ )
                {
                        $res_folder_str  .= join("|",$res[$i]);
                        if($i != sizeof($res)-1)
                        {
                                $res_folder_str  .="||";
                        }
                }
                $res_folder_str ="0".$res_folder_str; /// root without id

                $sql_action = "select menuid,sibling, title from left_menu order by sibling ";
                $res_action = $db->getAll($sql_action );
//              debug($res_action);
                $res_action_str = "";
                for($i= 0 ; $i < sizeof($res_action) ; $i++ )
                {
                        $res_action_str .= join("|",$res_action[$i]);
                        if($i != sizeof($res_action)-1)
                        {
                                $res_action_str .="||";
                        }
                }

                $render->assign('action_url',"?".$this->getURL()."&catalog_id=".$curent_catalog_id);
                $params = array
                        (
                                "action_url"    => "?".$this->getURL(),
                                "action_list"   => array("swap","insert_after","insert_before","sibling_delete"),
                                "insert_list_str" => str2db($res_action_str),
                                "res_folder_str" => $res_folder_str,
                        );
                $SB_HTML = $sb->Render($params);

                $render->assign('sibling',$SB_HTML);
                $render->assign("add_url", "?".$this->getURL()."&page=add");

                return "leftmenulist.tpl.php";
        }
};


?>